package com.rh.bmw4s.jpush;


import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;

import com.rh.bmw4s.comm.ConfigValue;
import com.rh.bmw4s.ui.WebShowActivity;
import com.rh.bmw4s.utills.LogUtils;
import com.rh.bmw4s.utills.SPUtils;

import org.json.JSONObject;

import cn.jpush.android.api.JPushInterface;


/**
 * Created by Administrator on 2017/4/17.
 */

public class PushService extends BroadcastReceiver {

    private NotificationManager nm;

    @Override
    public void onReceive(Context context, Intent intent) {
        if (null == nm) {
            nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        }

        Bundle bundle = intent.getExtras();
        LogUtils.d("onReceive - " + intent.getAction());

        if (JPushInterface.ACTION_REGISTRATION_ID.equals(intent.getAction())) {
            LogUtils.d("JPush用户注册成功");
            String registerID = bundle.getString(JPushInterface.EXTRA_REGISTRATION_ID);
            SPUtils.getInstance().put(ConfigValue.registerID, registerID);
        } else if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(intent.getAction())) {
            LogUtils.d("接受到推送下来的自定义消息");
            // showInspectorRecordNotification(context, bundle);
        } else if (JPushInterface.ACTION_NOTIFICATION_RECEIVED.equals(intent.getAction())) {
            LogUtils.d("接受到推送下来的通知");
            receivingNotification(context, bundle);
        } else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent.getAction())) {
            LogUtils.d("用户点击打开了通知");
            openNotification(context, bundle);
        } else if (JPushInterface.ACTION_RICHPUSH_CALLBACK.equals(intent.getAction())) {
            LogUtils.d("[MyReceiver] 用户收到到RICH PUSH CALLBACK: " + bundle.getString(JPushInterface.EXTRA_EXTRA));
            //在这里根据 JPushInterface.EXTRA_EXTRA 的内容处理代码，比如打开新的Activity， 打开一个网页等..
        } else if (JPushInterface.ACTION_CONNECTION_CHANGE.equals(intent.getAction())) {
            boolean connected = intent.getBooleanExtra(JPushInterface.EXTRA_CONNECTION_CHANGE, false);
            LogUtils.w("[MyReceiver]" + intent.getAction() + " connected state change to " + connected);
        } else {
            LogUtils.d("Unhandled intent - " + intent.getAction());
        }
    }

    private void showInspectorRecordNotification(Context context, Bundle bundle) {
//        String strTitle = bundle.getString(JPushInterface.EXTRA_TITLE);
//        String content = bundle.getString(JPushInterface.EXTRA_MESSAGE);
//        String extras = bundle.getString(JPushInterface.EXTRA_EXTRA);
//        //获取接收到推送时的系统时间
//        Calendar rightNow = Calendar.getInstance();
//        SimpleDateFormat fmt = new SimpleDateFormat("HH:mm:ss");
//        String date = fmt.format(rightNow.getTime());
//
//        RemoteViews customView = new RemoteViews(context.getPackageName(), R.layout.msg_item);
//        customView.setTextViewText(R.id.tv_msg_title, strTitle);
//        customView.setTextViewText(R.id.tv_msg_content, content);
//        customView.setTextViewText(R.id.tv_msg_date, date);
//
//        String myValue;
//        try {
//            JSONObject extrasJson = new JSONObject(extras);
//            myValue = extrasJson.optString("pushid");  //用户点开通知，根据extra的key和value进行判断
//        } catch (Exception e) {
//            LogUtils.w("Unexpected: extras is not a valid json", e);
//            return;
//        }
//        //自己创建通知
//        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context);
//
//        Intent transferIntent = new Intent(context, NewsDetailActivity.class);
//        transferIntent.putExtra(ConfigValue.pushNewsID, myValue);
//        transferIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
//        //transferIntent.putExtra(PushReceiverConstant.KEY_FORM_TYPE, pushType);
//        // 第二个参数不能写死，可以写一个随机数或者是时间毫秒数 保证唯一
//        PendingIntent pendingIntent = PendingIntent.getActivity(context, (int) (Math.random() * 100)
//                , transferIntent, PendingIntent.FLAG_UPDATE_CURRENT);
//
//        mBuilder.setSmallIcon(R.mipmap.icon_news_logo)
//                .setContent(customView)
//                .setPriority(Notification.PRIORITY_MAX)
//                .setOngoing(false)
//                .setContentIntent(pendingIntent);
//        Notification notify = mBuilder.build();
//        notify.flags |= Notification.FLAG_AUTO_CANCEL; // 点击通知后通知栏消失
//        // 通知id需要唯一，要不然会覆盖前一条通知
//        int notifyId = (int) System.currentTimeMillis();
//        NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
//        mNotificationManager.notify(notifyId, notify);
//
//        //将未读消息数加一
//        String unReadNews = SPUtils.getInstance().getString(ConfigValue.unReadNum, "0");
//        int i = Integer.parseInt(unReadNews) + 1;
//        SPUtils.getInstance().put(ConfigValue.unReadNum, String.valueOf(i));
    }

    private void receivingNotification(Context context, Bundle bundle) {
        String rece_id = bundle.getString(JPushInterface.EXTRA_MSG_ID);
        LogUtils.d(" rece_id : " + rece_id);
        String title = bundle.getString(JPushInterface.EXTRA_NOTIFICATION_TITLE);
        LogUtils.d(" title : " + title);
        String message = bundle.getString(JPushInterface.EXTRA_ALERT);
        LogUtils.d("message : " + message);
        String extras = bundle.getString(JPushInterface.EXTRA_EXTRA);
        LogUtils.d("extras : " + extras);

    }

    private void openNotification(Context context, Bundle bundle) {
        int anInt = SPUtils.getInstance().getInt(ConfigValue.userId);
        //LogUtils.d("ccc", anInt);
        String extras = bundle.getString(JPushInterface.EXTRA_EXTRA);
        String myUrl;
        String myMid;
        try {
            JSONObject extrasJson = new JSONObject(extras);
            myUrl = extrasJson.optString("url");  //用户点开通知，根据extra的key和value进行判断
            myMid = extrasJson.optString("mid");
        } catch (Exception e) {
            LogUtils.w("通知json错误", e);
            return;
        }
        Intent i = new Intent(context, WebShowActivity.class);
        //i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        i.putExtra("url", myUrl + anInt);
       // LogUtils.d("ccc", myUrl + anInt);
        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
        context.startActivity(i);

    }

//    //send msg to MainActivity
//    private void processCustomMessage(Context context, Bundle bundle) {
//        if (NewMainActivity.isForeground) {
//            String message = bundle.getString(JPushInterface.EXTRA_MESSAGE);
//            String extras = bundle.getString(JPushInterface.EXTRA_EXTRA);
//            Intent msgIntent = new Intent(NewMainActivity.MESSAGE_RECEIVED_ACTION);
//            msgIntent.putExtra(NewMainActivity.KEY_MESSAGE, message);
//            if (!ExampleUtil.isEmpty(extras)) {
//                try {
//                    JSONObject extraJson = new JSONObject(extras);
//                    if (extraJson.length() > 0) {
//                        msgIntent.putExtra(MainActivity.KEY_EXTRAS, extras);
//                    }
//                } catch (JSONException e) {
//
//                }
//
//            }
//            LocalBroadcastManager.getInstance(context).sendBroadcast(msgIntent);
//        }
//    }


}

